package pers.liyan.shi.springboot.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket工具类
 *
 * @author shily
 * @date 2019/6/18 9:57
 */
public class WebSocketUtils {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketUtils.class);

    /**
     * 存储在线用户的session
     */
    public static final Map<String, Session> ONLINE_USER_SESSIONS = new ConcurrentHashMap<>();

    /**
     * 发送WebSocket消息
     *
     * @param session 用户session
     * @param message 消息内容
     * @author shily
     * @date 2019/6/18 10:01
     */
    public static void sendMessage(Session session, String message) {
        if (session == null) {
            return;
        }
        RemoteEndpoint.Basic basicRemote = session.getBasicRemote();
        if (basicRemote == null) {
            return;
        }

        try {
            basicRemote.sendText(message);
        } catch (IOException e) {
            logger.error("sendMessage IOException", e);
        }
    }

    /**
     * 给所有用户发送消息
     * @param message 消息内容
     * @author shily
     * @date 2019/6/18 10:04
     */
    public static void sendMessageAll(String message) {
        ONLINE_USER_SESSIONS.forEach((sessionId, session) -> {
            sendMessage(session, message);
        });
    }
}
